const Bpmn = require('bpmn-engine');
const EventEmitter = require('events').EventEmitter;
const fs = require('fs');

let engine;
const activityIds = [];
const lineIds = [];
const curNodeIds = [];
let callbackFun;
let dataCs;
let errCs;
let isGetRest = false;

const listener = new EventEmitter();
function setListener() {
    listener.on('taken', (flow) => {
        lineIds.push(flow.id);
    });
    for (var i = 0; i < dataCs['nodeIds'].length; i++) {
        listener.once('wait-' + dataCs['nodeIds'][i], (child, instance) => {
            activityIds.push(child.activity.id);
            instance.signal(child.activity.id, {sirname: 's'});
        });
    }
    listener.on('start', (data) => {
        // console.log(engine.getPendingActivities().definitions[0].children);
        if (data.type == 'bpmn:UserTask') {
            var b = false;
            for (var i = 0; i < dataCs['nodeIds'].length; i++) {
                if (dataCs['nodeIds'][i] == data.id) {
                    b = true;
                    break;
                }
            }
            if (!b && !isGetRest) {
                isGetRest = true;
                goCallback();
            }
            try {
                const aas = engine.getPendingActivities().definitions[0].children;
                for (var i = 0; i < aas.length; i++) {
                    if (aas[i].taken && aas[i].type == 'bpmn:UserTask') {
                        goCallback();
                        return;
                    }
                }
            } catch(e) {}
        }
    });
    // 引擎结束的时候调用
    engine.on('end', (lastReportingDefinition) => {
        exeCallback();
    });
    // 引擎错误的时候调用
    engine.on('error', (err, eventSource) => {
        exeCallback();
    });
    return listener;
}
function goCallback() {
    setTimeout(function () {
        exeCallback();
    }, 0);
}
function exeCallback() {
    try {
        const activitys = engine.getPendingActivities().definitions[0].children;
        for (var i = 0; i < activitys.length; i++) {
            curNodeIds.push(activitys[i].id);
        }
    } catch(e) {}
    const dddd = { activityIds: activityIds, curNodeIds: curNodeIds, state: '', lineIds: lineIds };
    callbackFun(errCs, JSON.stringify(dddd));
}

function exe(data, callback) {
    callbackFun = callback;
    dataCs = data;

    engine = new Bpmn.Engine({
        name: data.engineName,
        source: data.engineSource
    });
    setListener();
    engine.execute({
        variables: data.variables,
        listener: listener
    }, (err, definition) => {
        errCs = err;
        if (err) {
            var dddd = { activityIds: [], curNodeIds: [], state: '', lineIds: [] };
            callbackFun(errCs, JSON.stringify(dddd));
        }
    });
};


exe(
    {
        engineName:  '测试',
        engineSource: fs.readFileSync('./ass/1005.bpmn'),
        variables: {level: 90, cashAmount: 10},
        nodeIds: [
            'UserTask_1fis4zu', 'UserTask_09l4c4c', 'UserTask_0ytm91g', 'UserTask_0agqui6', 'UserTask_1p6t0tx',
            "UserTask_0dryav8", "UserTask_0o1k9vf", "UserTask_1vqa3hz", 'UserTask_0s5t61g'
        ],
    },
    function (errCs, ret) {
        console.log('结果--------------');
        console.log(ret);
        console.log('结果--------------');
    }
);

/*

'UserTask_1fis4zu', 'UserTask_09l4c4c', 'UserTask_0ytm91g', 'UserTask_0agqui6', 'UserTask_1p6t0tx', 'UserTask_12tyq3e',
"UserTask_0dryav8", "UserTask_0o1k9vf", "UserTask_1vqa3hz", "UserTask_0s5t61g", "UserTask_1vzdkr2", 'UserTask_0b88olq'

return function (data, callback) {
    callbackFun = callback;
    dataCs = data;

    setListener();
    engine = new Bpmn.Engine({
        name: data.engineName,
        source: data.engineSource
    });
    engine.execute({
        variables: data.variables,
        listener: listener
    }, (err, definition) => {
        errCs = err;
        if (err) {
            var dddd = { activityIds: [], curNodeIds: [], state: '', lineIds: [] };
            callbackFun(errCs, JSON.stringify(dddd));
        }
    });
};
*/